package com.strangebreeds.therefromhere.engine;

import java.util.Properties;
import java.util.Vector;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import javax.mail.Multipart;
import javax.mail.BodyPart;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class EmailResults
{
	private Logger logger = Logger.getLogger(EmailResults.class);

	private String emailAddress;
	private String subject;
	private String body;

	{
		org.apache.log4j.PropertyConfigurator.configure("log4j.properties");
		logger.setLevel(Level.DEBUG);
	}

	public void setEmailAddress(String emailAddress)
	{
		this.emailAddress = emailAddress;
	}

	public void setSubject(String subject)
	{
		this.subject = subject;
	}

	public void setBody(String body)
	{
		this.body = body;
	}

	public boolean send()
	{
		Properties props = System.getProperties();
		props.put("mail.smtp.host", Configuration.getSMTPServer());
		props.put("mail.smtp.port", Configuration.getSMTPPort());
		props.put("mail.smtp.auth", "true");
		Session session = Session.getDefaultInstance(props, null);

		try
		{
			Message msg = new MimeMessage(session);

			msg.setFrom(new InternetAddress(Configuration.getFromAddress()));

			Vector<String> emailReceipients = new Vector<String>();
			emailReceipients.add(emailAddress);

			for (String currentAddress : emailReceipients)
			{
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
						currentAddress));
			}

			msg.setSubject(subject);

			// Create the message part
			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setText(body);

			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messageBodyPart);

			// Put parts in message
			msg.setContent(multipart);

			Transport transport = session.getTransport("smtp");
			transport.connect(	Configuration.getSMTPServer(),
								Configuration.getSMTPUsername(),
								Configuration.getSMTPPassword());
			
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();

			logger.debug("Send the email to " + emailAddress);
		}
		catch (AddressException ae)
		{
			logger.error("Got AddressException: " + ae.getMessage(), ae);
		}
		catch (MessagingException me)
		{
			logger.error("Got MessagingException: " + me.getMessage(), me);
		}

		return true;
	}
}
